<?php

/**
 * user actions.
 *
 * @package    appcemhti
 * @subpackage user
 * @author     Steve Cancès
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class userActions extends sfActions
{

    public function executeShow(sfWebRequest $request)
    {
        $this->sf_guard_user = Doctrine_Core::getTable('sfGuardUser')->find(array($request->getParameter('id')));
        $this->user = Doctrine_Core::getTable('user')->find(array($request->getParameter('id')));
        $this->forward404Unless($this->sf_guard_user);
    }

    public function executeNew(sfWebRequest $request)
    {
        $this->form = new sfGuardUserForm();
    }

    public function executeCreate(sfWebRequest $request)
    {
        $this->forward404Unless($request->isMethod(sfRequest::POST));

        $this->form = new sfGuardUserForm();

        //On rÃ©cupÃ¨re les paramÃ¨tres du form
            $params = $request->getParameter($this->form->getName());
            //On rÃ©cupÃ¨re le debut de l'adresse mail
            $password = explode("@", $params['email_address']);
            $params['password'] = $password[0];
            $params['password_bis'] = $password[0];
            $groups= array();
            $groups[0] = 2;
            $params['groups_list'] = $groups;
            $params['updated_at'] = date('Y-m-d H:i:s', time());
            $request->setParameter($this->form->getName(), $params);

        $this->processForm($request, $this->form);

        $this->setTemplate('new');
    }

    public function executeEdit(sfWebRequest $request)
    {
        $this->forward404Unless($sf_guard_user = Doctrine_Core::getTable('sfGuardUser')->find(array($request->getParameter('id'))), sprintf('Object sf_guard_user does not exist (%s).', $request->getParameter('id')));
        $this->forward404Unless($sf_guard_user->getId() != 1, sprintf("Impossible d'éditer l'admin"));
        $this->form = new sfGuardUserForm($sf_guard_user);
        $this->sf_guard_user = $sf_guard_user;
    }

    public function executeUpdate(sfWebRequest $request)
    {
        $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
        $this->forward404Unless($sf_guard_user = Doctrine_Core::getTable('sfGuardUser')->find(array($request->getParameter('id'))), sprintf('Object sf_guard_user does not exist (%s).', $request->getParameter('id')));
        $this->forward404Unless($sf_guard_user->getId() != 1, sprintf("Impossible d'éditer l'admin"));
        $this->userGroups = $sf_guard_user->getGroups();
        $this->form = new sfGuardUserForm($sf_guard_user);
        $this->sf_guard_user = $sf_guard_user;
        $groups= array();
        $iGroups = 0;
        foreach($sf_guard_user->getGroups() as $group)
        {
            $groups[$iGroups] = $group->getId();
            $iGroups = $iGroups+1;
        }
        
        $params = $request->getParameter($this->form->getName());
        $params['updated_at'] = date('Y-m-d H:i:s', time());
        $params['groups_list'] = $groups;
        $request->setParameter($this->form->getName(), $params);

        $this->processForm($request, $this->form);

        $this->setTemplate('edit');
    }

    protected function processForm(sfWebRequest $request, sfForm $form)
    {
        //On récupère les paramètres du form
        $params = $request->getParameter($form->getName());
        //On récupère le debut de l'adresse mail
        $username = explode("@", $params['email_address']);
        $params['username'] = $username[0];
        $request->setParameter($form->getName(), $params);

        $form->bind($params, $request->getFiles($form->getName()));
        if ($form->isValid())
        {
            $sf_guard_user = $form->save();
            if($user = Doctrine_Core::getTable('user')->find(array($request->getParameter('id'))))
            {
                
            }
            else
            {
                $user = new User();
            }
            $user->setIdUser($sf_guard_user->getId());
            $user->setLogin($params['username']);
            $user->setSfguarduserId($sf_guard_user->getId());
            $user->save();
            $user->calculerDroitLots();
            $this->redirect('user/show?id='.$user->getIdUser());
        }
    }
    
    protected function isAdmin()
    {
        return ($this->getUser()->getGuardUser()->isAdmin() == true);
    }


    //AJAX
    
    protected function responseJSON($status, $msg)
    {
        $response = array(
            "status" => $status,
            "msg" => $msg
        );
        return $this->renderText(json_encode($response));
    }

    public function executePromouvoirUser(sfWebRequest $request)
    {
        if ($request->isXmlHttpRequest())
        {
            $idUser= intval($request->getParameter("id"));
            //Si l'utilisateur n'est pas le superadmin
            if($idUser != 1)
            {
                //Si l'utilisateur ne modifie pas son compte
                if($idUser != $this->getUser()->getGuardUser()->getId())
                {
                    $sf_guard_user = Doctrine_Core::getTable('sfGuardUser')->find(array($idUser));
                    $sf_guard_user->promouvoir();
                    return $this->responseJSON(
                            "success",
                            $sf_guard_user->getFirstName()." ".$sf_guard_user->getLastName()." est maintenant administrateur"
                    );
                }
                else
                {
                    return $this->responseJSON("error", "Impossible de modifier votre propre statut");
                }
            }
            else
            {
                return $this->responseJSON("error", "Impossible de modifier le statut du super administrateur");
            }
        }
    }

    public function executeDegraderUser(sfWebRequest $request)
    {
        if ($request->isXmlHttpRequest())
        {
            $idUser= intval($request->getParameter("id"));
            //Si l'utilisateur n'est pas le superadmin
            if($idUser != 1)
            {
                //Si l'utilisateur ne modifie pas son compte
                if($idUser != $this->getUser()->getGuardUser()->getId())
                {
                    $sf_guard_user = Doctrine_Core::getTable('sfGuardUser')->find(array($idUser));
                    $sf_guard_user->degrader();
                    return $this->responseJSON(
                            "success",
                            $sf_guard_user->getFirstName()." ".$sf_guard_user->getLastName()." n'est maintenant plus administrateur"
                    );
                }
                else
                {
                    return $this->responseJSON("error", "Impossible de modifier votre propre statut");
                }
            }
            else
            {
                return $this->responseJSON("error", "Impossible de modifier le statut du super administrateur");
            }
        }
    }

    public function executeActiverUser(sfWebRequest $request)
    {
        if ($request->isXmlHttpRequest())
        {
            $idUser= intval($request->getParameter("id"));
            //Si l'utilisateur n'est pas le superadmin
            if($idUser != 1)
            {
                //Si l'utilisateur ne modifie pas son compte
                if($idUser != $this->getUser()->getGuardUser()->getId())
                {
                    $sf_guard_user = Doctrine_Core::getTable('sfGuardUser')->find(array($idUser));
                    $sf_guard_user->activer();
                    return $this->responseJSON(
                            "success",
                            "Le compte de ".$sf_guard_user->getFirstName()." ".$sf_guard_user->getLastName()." est maintenant activé"
                    );
                }
                else
                {
                    return $this->responseJSON("error", "Impossible de modifier votre propre statut");
                }
            }
            else
            {
                return $this->responseJSON("error", "Impossible de modifier le statut du super administrateur");
            }
        }
    }
  
    public function executeDesactiverUser(sfWebRequest $request)
    {
        if ($request->isXmlHttpRequest())
        {
            $idUser= intval($request->getParameter("id"));
            //Si l'utilisateur n'est pas le superadmin
            if($idUser != 1)
            {
                //Si l'utilisateur ne modifie pas son compte
                if($idUser != $this->getUser()->getGuardUser()->getId())
                {
                    $sf_guard_user = Doctrine_Core::getTable('sfGuardUser')->find(array($idUser));
                    $sf_guard_user->desactiver();
                    return $this->responseJSON(
                            "success",
                            "Le compte de ".$sf_guard_user->getFirstName()." ".$sf_guard_user->getLastName()." est maintenant désactivé"
                    );
                }
                else
                {
                    return $this->responseJSON("error", "Impossible de modifier votre propre statut");
                }
            }
            else
            {
                return $this->responseJSON("error", "Impossible de modifier le statut du super administrateur");
            }
        }
    }
    
    
    public function executeListLot(sfWebRequest $request)
    {
        if ($request->isXmlHttpRequest())
        {
            $idUser= intval($request->getParameter("idUser"));
            $sSearch = $request->getParameter("sSearch");
            $iSortCol_0 = $request->getParameter("iSortCol_0");
            $sSortDir_0 = $request->getParameter("sSortDir_0");
            $iDisplayStart = $request->getParameter("iDisplayStart");
            $iDisplayLength = $request->getParameter("iDisplayLength");
            $page = number_format($iDisplayStart / $iDisplayLength) + 1;
            
            $user = Doctrine_Core::getTable('User')->find(array($idUser));
            
            
            $q = Doctrine_Core::getTable('lot')->getLotDroitDatatable($sSearch, $iSortCol_0, $sSortDir_0);
            
            
            $this->pager = new sfDoctrinePager(
                'lot',
                sfConfig::get(2)
            );
            $this->pager->setQuery($q);
            $this->pager->setMaxPerPage($iDisplayLength);
            $this->pager->setMaxRecordLimit($iDisplayLength);
            $this->pager->setPage($page);
            $this->pager->init();
            
            $pager = $this->pager;

            $this->getContext()->getConfiguration()->loadHelpers('Url', 'Date');
            $aaData = array();
            $list = $pager->getResults();
           
            
            foreach ($list as $v)
            {
                $droitDef = $v->droitDefaultSurLot($user->getIdUser());
                $droits = $v->getDroitsUtilisateur();
                $droit = null;
                foreach ($droits as $droitCourant)
                {
                    if($droitCourant->getIdUser() == $idUser) $droit = $droitCourant;
                }
                
                $actions = "";
                $niLectureNiEcriture = '<a id="modifDroit_'.$v->getIdLot().'_1" class="submit modifDroit" href="">Ni lecture ni écriture</a>';
                $lectureSeulement = '<a id="modifDroit_'.$v->getIdLot().'_2" class="submit modifDroit" href="">lecture seulement</a>';
                $lectureEtEcriture = '<a id="modifDroit_'.$v->getIdLot().'_3" class="submit modifDroit" href="">lecture et écriture</a>';
                $droitDefaut = '<a id="deleteDroit_'.$v->getIdLot().'" class="submit deleteDroit" href="">droit par défaut</a>';
                $actions = $niLectureNiEcriture.$lectureSeulement.$lectureEtEcriture.$droitDefaut;
                
                //$consulter = '<a class="submit" href="lot/show/id_lot/' . $v->getIdLot() . '">Consulter</a>';
                if($v->getConfidentiel() == 1) $conf = "Oui"; else $conf = "Non";
                $userGuard = Doctrine_Core::getTable('sfGuardUser')->find(array($v->getUser()->getIdUser()));
                
                $fournisseur = "";
                if($v->getIdFournisseur()) $fournisseur = $v->getFournisseur()->getNom();

                if($droit == null)
                {
                    $libelleDroitDef = $droitDef->getLibelle();
                    $libelleDroitSpec = "";
                }
                else
                {
                    if($droit->getDroitSpecifique() == 1)
                    {
                        $libelleDroitDef = "<s>".$droitDef->getLibelle()."</s>";
                        $libelleDroitSpec = $droit->getTypeDroit()->getLibelle();
                    }
                    else
                    {
                        $libelleDroitDef = $droit->getTypeDroit()->getLibelle();
                        $libelleDroitSpec = "";
                    } 
                }
                $aaData[] = array(
                    "0" => $v->getIdLot(),
                    "1" => $v->getNom(),
                    "2" => $fournisseur,
                    "3" => $v->getDateTimeObject('date_recep')->format('d/m/Y'),
                    "4" => $v->getMatiere()->getLibelle(),
                    "5" => $conf,
                    "6" => $userGuard->getFirstName() . " " . $userGuard->getLastName(),
                    "7" => $libelleDroitDef,
                    "8" => $libelleDroitSpec,
                    "9" => $actions,
                );
            }
            $output = array(
            "iTotalRecords" => count($pager),
            "iTotalDisplayRecords" => count($pager),
            "aaData" => $aaData,
            );

            return $this->renderText(json_encode($output));
        }
    }
    
    public function executeMAJDroits(sfWebRequest $request)
    {
        if ($request->isXmlHttpRequest())
        {
            $users = Doctrine_Core::getTable('User')->findAll();
            foreach ($users as $user)
            {
                $user->calculerDroitLots();
            }
            return $this->responseJSON("success", "Les droits des utilisateurs sont à jour.");
        }
    }
    
}
